<template>
  <div class="dept">
    <el-card>
      <!-- 查询区 -->
      <el-form :inline="true" :model="queryInfo" ref="queryFormRef" size="small">
        <el-form-item label="选择部门" prop="id">
          <dept-select :value.sync="queryInfo.id" style="width:220px" :disableBranchNodes="false" />
        </el-form-item>

        <el-form-item label="类型" prop="deptType">
          <el-select v-model="queryInfo.deptType" :disabled="deptDisable">
            <el-option label="全部" value></el-option>
            <el-option label="公司" :value="0"></el-option>
            <el-option label="部门" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleQueryReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 操作区 -->
      <div class="operation">
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="addDeptForm">添加</el-button>
      </div>
      <!-- 表格 -->
      <el-table
        :data="departmentData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        default-expand-all
        tooltip-effect="dark"
        v-loading="loading"
        :header-cell-style="{ background: '#f8f8f9', color: '#515a6e' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="deptName" label="部门名称" width="220px"></el-table-column>
        <!-- <el-table-column
          prop="deptDesc"
          label="部门描述"
          width="220"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>-->
        <el-table-column label="部门类型" align="center">
          <template slot-scope="scope">
            <span>
              <el-tag size="small" effect="dark" v-if="scope.row.deptType === 0">公司</el-tag>
              <el-tag size="small" type="success" effect="dark" v-else>部门</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="deptPhone" label="部门电话" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="deptFax" label="部门传真" align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column prop="deptPhone" label="部门电话"></el-table-column> -->
        <!-- <el-table-column prop="deptFax" label="部门传真"></el-table-column> -->
        <!-- <el-table-column prop="deptDesc" label="部门描述" width="220" :show-overflow-tooltip="true"></el-table-column> -->

        <el-table-column label="创建时间" width="140" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime | formatDate }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="更新时间" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime | formatTime }}</span>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleMdfOneDept(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelOneDept(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeDialog"
    >
      <el-form
        ref="deptFormRef"
        :model="deptForm"
        size="medium"
        label-width="80px"
        :rules="deptRules"
        inline
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级部门" prop="pId">
              <dept-select
                :value.sync="deptForm.pId"
                :disableBranchNodes="false"
                style="width:220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="deptForm.deptName" clearable placeholder="部门"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门类型" prop="deptType">
              <el-select v-model="deptForm.deptType" clearable>
                <el-option label="公司" :value="0"></el-option>
                <el-option label="部门" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门电话" prop="deptPhone">
              <el-input v-model="deptForm.deptPhone" clearable placeholder="部门电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="部门传真" prop="deptFax">
              <el-input v-model="deptForm.deptFax" clearable placeholder="部门传真"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="部门描述" prop="deptDesc">
          <el-input type="textarea" v-model="deptForm.deptDesc" rows="5" placeholder="部门描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
        <el-button @click="handleFormReset">重 置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  delOneDeptApi,
  getDeptTreeApi,
  // listDeptTreeByQo,
  insertDeptApi,
  mdfDeptApi,
  getDeptById,
} from "@/api/dept";

export default {
  data() {
    const checkPhone = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入手机号码"));
      }
      // eslint-disable-next-line no-useless-escape
      let myreg = /^1[3456789]\d{9}$/;
      if (!myreg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    return {
      state: "",
      title: "",
      queryInfo: {
        //部门编号
        id: undefined,
        //部门类型
        deptType: "",
      },

      dialogVisible: false,
      departmentData: [],
      deptForm: {
        pId: undefined,
        deptName: "",
        deptType: "",
        deptPhone: "",
        deptFax: "",
        deptDesc: "",
      },
      deptRules: {
        pId: [
          {
            required: true,
            message: "请选择上级部门",
            trigger: "blur",
          },
        ],
        deptName: [
          {
            required: true,
            message: "请输入部门名称名",
            trigger: "blur",
          },
        ],
        deptType: [
          {
            required: true,
            message: "请选择部门类型",
            trigger: "blur",
          },
        ],
        deptPhone: [{ validator: checkPhone, trigger: "blur" }],
      },
      loading: false,
      deptDisable: true,
    };
  },
  methods: {
    //获取dept数据 无参数
    async getDepartments() {
      try {
        this.loading = true;
        const { data, code } = await getDeptTreeApi(this.queryInfo);
        if (code !== 200) return;
        this.departmentData = data;
      } finally {
        this.loading = false;
      }
    },
    closeDialog() {
      this.handleFormReset("deptFormRef");
    },
    // 处理添加部门
    addDeptForm() {
      this.state = "addDept";
      this.title = "添加部门";
      this.dialogVisible = true;
    },
    handleQueryReset() {
      this.$refs.queryFormRef.resetFields();
      this.getDepartments();
    },
    //处理修改部门
    async handleMdfOneDept(dept) {
      this.state = "mdfDept";
      this.title = "修改部门";
      const { data, code } = await getDeptById(dept.id);
      if (code !== 200) return;
      this.deptForm = data;
      this.dialogVisible = true;
    },
    //删除部门
    handleDelOneDept(dept) {
      this.confirm(`删除部门${dept.deptName}`, async () => {
        const { code } = await delOneDeptApi(dept.id);
        if (code !== 200) return Promise.reject();
        this.getDepartments();
      });
    },
    //关键字查询
    handleQuery() {
      this.getDepartments();
    },
    // 封装应答框
    confirm(title, cb, operation = "删除") {
      this.$confirm(`此操作将${title}, 是否继续?`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await cb();
            this.$message.success(`${operation}成功!`);
          } catch {
            this.$message.error(`${operation}失败!`);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消${operation}`,
          });
        });
    },
    // 重置表单
    handleFormReset() {
      this.deptForm = {};
      this.$refs.deptFormRef.resetFields();
      // this.$nextTick(() => {
      //   if (this.$refs[formName] !== undefined) {
      //
      //   }
      // });
    },

    //提交表单
    handleFormSubmit() {
      this.$refs.deptFormRef.validate(async (valid) => {
        if (!valid) return;
        if (this.state === "addDept" || this.state === "addSonDept") {
          const { code } = await insertDeptApi(this.deptForm);
          if (code !== 200) return;
          this.$message.success("添加部门成功");
        } else if (this.state === "mdfDept") {
          const { code } = await mdfDeptApi(this.deptForm);
          if (code !== 200) return;
          this.$message.success("修改部门信息成功");
        }
        this.dialogVisible = false;
        this.getDepartments();
      });
    },
  },
  created() {
    this.getDepartments();
  },
  watch: {
    queryInfo: {
      handler(newVal) {
        if (newVal.id) {
          this.deptDisable = false;
        } else {
          this.deptDisable = true;
        }
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.operation {
  .el-button {
    margin-bottom: 18px;
  }
}
</style>
